﻿using UnityEditor;
using System.IO;
using UnityEngine;
using System.Collections.Generic;

namespace CGF
{
    public class ChangeTextureMD5
    {

        [MenuItem("CGFramework/混淆/改变所有图片MD5", priority = -900)]
        private static void ChangeAllTextureMD5()
        {
            string dir = EditorUtility.OpenFolderPanel("指定目录", "Assets", "");

            if (!EditorUtility.DisplayDialog("提示", $"确定修改目录\n\n{dir}\n\n下的所有图片MD5吗？该操作不可逆", "确定")) return;

            List<string> filePaths = new List<string>();
            filePaths.AddRange(Directory.GetFiles(dir, "*jpg", SearchOption.AllDirectories));
            filePaths.AddRange(Directory.GetFiles(dir, "*png", SearchOption.AllDirectories));

            int total = filePaths.Count;
            for (int i = 0; i < total; i++)
            {
                ChangeOneTextureMD5(filePaths[i]);
                EditorUtility.DisplayProgressBar("改变图片MD5", "进度: " + (i + 1) + "/" + total, (i + 1) / (float)total);
            }
            EditorUtility.ClearProgressBar();

            Debug.Log($"全部图片({total}张)改变MD5完成");
            EditorUtility.DisplayDialog("标题", $"全部图片({total}张)改变MD5完成", "确定");
        }

        private static void ChangeOneTextureMD5(string path)
        {
            Debug.Log($"改变图片MD5：{path}");
            Texture2D oldTex = new Texture2D(0, 0, TextureFormat.RGB24, false);
            oldTex.LoadImage(File.ReadAllBytes(path));
            int markW = oldTex.width;
            int markH = oldTex.height;
            int randomChangeCol = Random.Range(0, markW);
            int randomChangeRow = Random.Range(0, markH);
            for (int r = 0; r < markH; r++)
            {
                bool isBreak = false;
                for (int c = 0; c < markW; c++)
                {
                    if (c == randomChangeCol && r == randomChangeRow)
                    {
                        Color color = oldTex.GetPixel(c, r);
                        color.r = color.r == 1 ? color.r - 0.01f : color.r + 0.01f;
                        oldTex.SetPixel(c, r, color);
                        isBreak = true;
                        break;
                    }
                }
                if (isBreak) break;
            }
            oldTex.Apply();
            if (path.EndsWith(".jpg"))
            {
                File.WriteAllBytes(path, oldTex.EncodeToJPG());
            }
            else
            {
                File.WriteAllBytes(path, oldTex.EncodeToPNG());
            }
            AssetDatabase.Refresh();
        }
    }
}